package com.mayikt.swagger.filter;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.RateLimiter;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @Name SeckillFilter
 * @Author 枫火
 * @Date 2021/7/18 21:01
 * @Description 秒杀过滤器
 **/
//@Component
//public class SeckillFilter implements GlobalFilter, Ordered {
//    // 创建一个限流器，参数代表每秒生成1个令牌数（用户限流率设置 每秒限制1个请求）
////    private RateLimiter rateLimiter = RateLimiter.create(1);
//    LoadingCache<String, RateLimiter> ipRequestCaches = CacheBuilder.newBuilder()
//            .maximumSize(1000)// 设置缓存个数
//            .expireAfterWrite(1, TimeUnit.MINUTES)
//            .build(new CacheLoader<String, RateLimiter>() {
//                @Override
//                public RateLimiter load(String s) throws Exception {
//                    return RateLimiter.create(1);// (限流每秒1个令牌响应)
//                }
//            });
//
//    @SneakyThrows
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpResponse response = exchange.getResponse();
//        ServerHttpRequest request = exchange.getRequest();
//        HttpHeaders header = response.getHeaders();
//        header.add("Content-Type", "application/json; charset=UTF-8");
//        RequestPath path = request.getPath();
//        // 根据用户请求地址进行设置限流（可以看做对不同用户进行限定）不同用户每秒可以访问一次
//        RateLimiter rateLimiter = ipRequestCaches.get(request.getURI().toString());
//        boolean tryAcquire = rateLimiter.tryAcquire();
//        if (!tryAcquire) {
//            JSONObject jsonObject = setResultErrorMsg("当前访问用户过多，请稍后重试");
//            DataBuffer buffer = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
//            return response.writeWith(Mono.just(buffer));
//        }
//
//        // 放行转发到秒杀服务
//        return chain.filter(exchange);
//    }
//
//    /**
//     * 设置优先级，数值越小越先执行
//     * @return
//     */
//    @Override
//    public int getOrder() {
//        return 1;
//    }
//    private JSONObject setResultErrorMsg(String msg) {
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("code", "500");
//        jsonObject.put("msg", msg);
//        return jsonObject;
//    }
//}
